package com.sy.service.impl;

import com.sy.dao.UserDao;
import com.sy.dao.impl.UserDaoImpl;
import com.sy.dto.Result;
import com.sy.entity.User;
import com.sy.service.UserService;
import com.sy.vo.LoginParams;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.Objects;

import static com.sy.constant.RegexConstant.STRONG_PWD_REGEX;

public class UserServiceImpl extends AbstractBaseServiceImpl implements UserService {
    private UserDao userDao = new UserDaoImpl();

    @Override
    public void regist(String userName, String userPwd, String userPwdConfirm) {
        //1.注册操作中保证用户名不能重复，密码必须是强密码类型，两次输入的密码必须一致
        throwIfBlank(userName, "用户名不能为空");
        User user = userDao.getUserbyUserName(userName);
        throwIfNotNull(user, "用户名已存在");
        throwIfTrue(StringUtils.isBlank(userPwd) || StringUtils.isBlank(userPwdConfirm),
                "密码不能为空");
        throwIfNotMatch(userPwd, STRONG_PWD_REGEX, "密码必须是强密码类型");
        throwIfStringsNotEquals(userPwd, userPwdConfirm, "两次密码必须一致");
        //2.将用户数据写入数据库中
        boolean success = userDao.addUser(userName, DigestUtils.md5Hex(userPwd));
        throwIfFalse(success, "注册失败");

    }

    @Override
    public User login(LoginParams loginParams, String correctValidateCode) {
        System.out.println(correctValidateCode);
        String userName = loginParams.getUserName();
        String userPwd = loginParams.getUserPwd();
        String validateCode = loginParams.getValidateCode();
        throwIfBlank(userName, "用户名不能为空");
        User user = userDao.getUserbyUserName(userName);
        throwIfNull(user, "用户不存在");
        throwIfBlank(userPwd, "密码不能为空");
        throwIfStringsNotEquals(user.getPwd(), DigestUtils.md5Hex(loginParams.getUserPwd()), "密码错误");
        throwIfBlank(validateCode, "验证码不得为空");
        throwIfStringsNotEqualsIgnoreCase(correctValidateCode, loginParams.getValidateCode(), "验证码不正确");
        return user;
    }

    @Override
    public User autoLogin(String cookieUserInfo) {
        List<User> users = userDao.getAllUsers();
        User loginUser = null;
        for (User user : users) {
            String userName = user.getName();
            String userPwd = user.getPwd();
            if (StringUtils.equals(cookieUserInfo, DigestUtils.md5Hex(userName + "," + userPwd))) {
                loginUser = user;
                break;
            }
        }
        if (Objects.nonNull(loginUser)) {
            return loginUser;
        }
        return null;
    }
}
